package com.web.controller;

import com.alibaba.fastjson2.JSON;
import com.web.entity.ResponseResult;
import com.web.entity.Student;
import com.web.service.StudentService;
import com.web.service.impl.StudentServiceimpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;



@WebServlet("/SelectById")
//通过id查询
public class SelectById extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        StudentService studentService = new StudentServiceimpl();
        //设置请求编码
        req.setCharacterEncoding("UTF-8");
        //设置响应编码
        resp.setCharacterEncoding("UTF-8");
        //设置响应类型
        resp.setContentType("application/json;charset=UTF-8");

        // 获取请求参数（学生 id）
        int id = Integer.parseInt(req.getParameter("id"));
        // 调用 Service 方法查询学生信息
        Student student = studentService.findStudentById(id);
        // 构造响应结果
        ResponseResult result;
        if (student != null) {
            result = new ResponseResult(200, student, "ok");
        } else {
            result = new ResponseResult(404, "学生不存在", "error");
        }
        // 将结果转换为 JSON 并返回
        String json = JSON.toJSONString(result);
        resp.getWriter().write(json);
    }
}
